import { Http } from '@/@nasty/Axios';
import { util } from '@/@nasty/Util';
import Upload from '@/@nasty/components/Upload';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProColumns, ProFormInstance, ProFormItem, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Checkbox, Divider, Tree, message } from 'antd';
import React, { useEffect } from 'react';
import { FC, cloneElement, useCallback, useRef, useState } from 'react';

const addChildrenTreeData = (list: any[], key: any, children: any[]): any[] =>
    list.map((node) => {
        if (node.key === key) {
            return {
                ...node,
                children,
            };
        }
        if (node.children) {
            return {
                ...node,
                children: addChildrenTreeData(node.children, key, children),
            };
        }
        return node;
    });

async function getPageApi(
    params: any,
    options?: any,
) {
    return new Promise<any>((resolve, reject) => {
        Http.post("/System/Role/GetRolePage", { ...params }, { isLower: true })
            .then((data) => {
                resolve(data);
            }).catch((e) => {
                reject(e)
            })
    });

}


const SelectDepartmentModel: FC<any> = (props) => {
    const { params, trigger, multiple, defaultValue, onSelect } = props;
    const [messageApi, contextHolder] = message.useMessage();
    const [depts, setDepts] = useState<any[]>([]);
    const [checkedKeys, setCheckedKeys] = useState<any[]>([]);
    const [tiledDepts, setTiledDepts] = useState<any[]>([]);
    const [expandedKeys, setExpandedKeys] = useState<any[]>([]);

    useEffect(() => {
        loadDept(null, null, null);
        return () => {
        };
    }, []);

    const loadDept = (parentId: string | null, success: any, error: any) => {
        Http.post("/System/Department/GetDepartments", { ParentId: parentId })
            .then((data) => {
                let items = data || [];
                items = items.map((t: any) => { return { title: `${t.Name}（${t.Code}）`, key: t.Id, isLeaf: t.IsLeaf, parentKey: t.ParentId, serialNumber: t.SerialNumber } })

                let tileds = [...tiledDepts, ...items];
                tileds = util.filterByField(tileds, "key");

                setTiledDepts(tileds);
                if (success) {
                    success(items);
                } else {
                    if (error)
                        error()
                    else
                        setDepts(items);
                }

            }).catch((e) => {
                if (error) error();
                message.error("加载部门数据失败");
            })
    }

    const onLoadDeptData = ({ key, children }: any) =>

        new Promise<void>((resolve) => {
            if (children) {
                resolve();
                return;
            }

            loadDept(key,
                (items: any) => {
                    setDepts((origin) => addChildrenTreeData(origin, key, items),);
                    resolve();
                }, () => {
                    resolve();
                }
            );

        });


    const getDefaultValue = () => {
        if (typeof defaultValue === 'function') {
            return defaultValue();
        }
        else {
            return defaultValue;
        }

    }
    const check = (data: any) => {
        let keys = data.checked || [];
        if (multiple === true) {
            setCheckedKeys(keys);
        } else {
            let lastKey = keys[keys.length - 1];
            let items = lastKey == null ? [] : [lastKey];
            setCheckedKeys(items);
        }
    }

    const getSelectData = () => {
        let items = tiledDepts.filter((t: any) => checkedKeys.includes(t.key));
        items = items.map((t: any) => { return { value: t.key || t.Id, label: t.label || t.Name || t.title } });
        return items;
    }

    return (
        <>
            {contextHolder}
            <ModalForm
                title={"选择部门"}
                trigger={trigger}
                width={"552px"}
                modalProps={{ okButtonProps: {} }}
                onFinish={async (value) => {
                    if (checkedKeys.length === 0) {
                        message.warning('请至少选择一项');
                        return false;
                    }


                    let rows = getSelectData();
                    let items = multiple ? rows : rows[0];
                    onSelect(items);
                    return true;
                }}

                onOpenChange={(v) => {
                    if (v) {
                        let defs = getDefaultValue() || [];
                        if (!Array.isArray(defs)) defs = [defs];
                        let defKeys = defs.map((t: any) => t.value);
                        setCheckedKeys(defKeys);
                        setExpandedKeys(defKeys);
                    }
                }}
            >


                <Tree
                    checkable
                    treeData={depts}
                    checkedKeys={checkedKeys}
                    checkStrictly={true}
                    expandedKeys={expandedKeys}
                    onCheck={(data: any) => { check(data); }}
                    onExpand={(data: any) => { setExpandedKeys(data); }}
                    loadData={onLoadDeptData}
                />
            </ModalForm>
        </>
    );
};


export { SelectDepartmentModel };
